package top.pcat.util;

import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedPacketUtil {

    /**
     * 发红包算法，金额参数以分为单位
     * @param totalAmount
     * @param totalPeopleNum
     * @return
     */
    public static List<Integer> divideRedPackage(Integer totalAmount, Integer totalPeopleNum) {
        List<Integer> amountList = new ArrayList<Integer>();

        if (totalAmount>0 && totalPeopleNum>0){
            Integer restAmount = totalAmount;
            Integer restPeopleNum = totalPeopleNum;

            Random random = new Random();
            for (int i = 0; i < totalPeopleNum - 1; i++) {
                // 随机范围：[1，剩余人均金额的两倍)，左闭右开

                int amount = random.nextInt(restAmount / restPeopleNum * 2 - 1) + 1;
                restAmount -= amount;
                restPeopleNum--;
                amountList.add(amount);
            }
            //循环完毕，剩余的金额即为最后一个随机金额，也需要将其加入到列表中
            amountList.add(restAmount);
        }

        return amountList;
    }


    @Test
    public void one() throws Exception{
        //总金额单位为分
        Integer amout=1000;
        //总人数-红包个数
        Integer total=10;
        //得到随机金额列表
        List<Integer> list=RedPacketUtil.divideRedPackage(amout,total);
        System.out.println("总金额={"+amout+"}分，总个数={"+total+"}个");

        //用于统计生成的随机金额之和是否等于总金额
        Integer sum=0;
        //遍历输出每个随机金额
        for (Integer i:list){
            System.out.printf("随机金额为："+i+"分，即 "+new BigDecimal(i.toString()).divide(new BigDecimal(100))+"元\n");
            sum += i;
        }
        System.out.printf("所有随机金额叠加之和="+sum+"分\n");
    }
}